我們學習了這麼多元件如何使用今天我們就將他們整合起來變成一個基本的鬧鐘
首先我們需要
一個pickview 用來選擇時間
一個button 用來確定時間
一個Label 顯示時間
我們先將元件拉好並且將我們所需要的變數宣告好後
@IBOutlet weak var ShowTime: UILabel!
@IBOutlet weak var EnterTime: UIButton!
@IBOutlet weak var Timechoce: UIPickerView!
var HourSelect:Int = 0
var MinSelect:Int = 0
var Hour = [Int](0...23)
var Min = [Int] (0...59)
再來我們將我們所學到的pickview套上
extension MainViewController: UIPickerViewDelegate, UIPickerViewDataSource {
func numberOfComponents(in pickerView: UIPickerView) -> Int {
return 2
}
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
if component == 0 {
return Hour.count
} else {
return Min.count
}
}
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
if component == 0 {
HourSelect = Hour[row]
} else {
MinSelect = Min[row]
}
}
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
if component == 0 {
if Hour[row] < 10 {
return "0\(Hour[row])"
} else {
return "\(Hour[row])"
}
} else {
if Min[row] < 10 {
return "0\(Min[row])"
} else {
return "\(Min[row])"
}
}
}
}
然後在button裡將我們存起的變數顯示出來
@IBAction func PutEle(_ sender: UIButton) {
ShowTime.text = "\(HourSelect) : \(MinSelect)"
}
最後記得加上這兩句
pickview.delegate = self
pickview.dataSource = self
這樣就可以正常顯示了讓我們來看看成果